package business

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/business"
	businessReq "github.com/flipped-aurora/gin-vue-admin/server/model/business/request"
	businessRes "github.com/flipped-aurora/gin-vue-admin/server/model/business/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/service"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"go.uber.org/zap"
)

type EmailTemplateApi struct {
}

var emailTemplateService = service.ServiceGroupApp.BusinessServiceGroup.EmailTemplateService

// CreateEmailTemplate 创建短息模板
// @Tags EmailTemplate
// @Summary 创建短息模板
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.EmailTemplate true "创建短息模板"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /emailTemplate/createEmailTemplate [post]
func (emailTemplateApi *EmailTemplateApi) CreateEmailTemplate(c *gin.Context) {
	var emailTemplate business.EmailTemplate
	err := c.ShouldBindJSON(&emailTemplate)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	verify := utils.Rules{
		"Name": {utils.NotEmpty()},
	}
	if err := utils.Verify(emailTemplate, verify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//当不是管理员时
	if isAdmin == 2 {
		emailTemplate.UserId = userId
	}
	if err := emailTemplateService.CreateEmailTemplate(&emailTemplate); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteEmailTemplate 删除短息模板
// @Tags EmailTemplate
// @Summary 删除短息模板
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.EmailTemplate true "删除短息模板"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /emailTemplate/deleteEmailTemplate [delete]
func (emailTemplateApi *EmailTemplateApi) DeleteEmailTemplate(c *gin.Context) {
	var emailTemplate business.EmailTemplate
	err := c.ShouldBindJSON(&emailTemplate)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//当不是管理员时
	if isAdmin == 2 {
		emailTemplate.UserId = userId
	}
	if err := emailTemplateService.DeleteEmailTemplate(emailTemplate); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteEmailTemplateByIds 批量删除短息模板
// @Tags EmailTemplate
// @Summary 批量删除短息模板
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除短息模板"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /emailTemplate/deleteEmailTemplateByIds [delete]
func (emailTemplateApi *EmailTemplateApi) DeleteEmailTemplateByIds(c *gin.Context) {
	var IDS request.IdsReq
	err := c.ShouldBindJSON(&IDS)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	var userIdInfo uint
	//当不是管理员时
	if isAdmin == 2 {
		userIdInfo = userId
	}
	if err := emailTemplateService.DeleteEmailTemplateByIds(IDS, userIdInfo); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateEmailTemplate 更新短息模板
// @Tags EmailTemplate
// @Summary 更新短息模板
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.EmailTemplate true "更新短息模板"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /emailTemplate/updateEmailTemplate [put]
func (emailTemplateApi *EmailTemplateApi) UpdateEmailTemplate(c *gin.Context) {
	var emailTemplate business.EmailTemplate
	err := c.ShouldBindJSON(&emailTemplate)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//管理员判断
	if isAdmin == 2 {
		emailTemplate.UserId = userId
	}
	if err := emailTemplateService.UpdateEmailTemplate(emailTemplate); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindEmailTemplate 用id查询短息模板
// @Tags EmailTemplate
// @Summary 用id查询短息模板
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query business.EmailTemplate true "用id查询短息模板"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /emailTemplate/findEmailTemplate [get]
func (emailTemplateApi *EmailTemplateApi) FindEmailTemplate(c *gin.Context) {
	var emailTemplate business.EmailTemplate
	err := c.ShouldBindQuery(&emailTemplate)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)

	//管理员判断
	if isAdmin == 2 {
		emailTemplate.UserId = userId
	}
	reemailTemplate, err := emailTemplateService.GetEmailTemplate(emailTemplate.ID, emailTemplate.UserId)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	if reemailTemplate.ID == 0 {
		response.FailWithMessage("没有该数据", c)
		return
	}
	response.OkWithData(gin.H{"reemailTemplate": reemailTemplate}, c)

}

// GetEmailTemplateList 分页获取短息模板列表
// @Tags EmailTemplate
// @Summary 分页获取短息模板列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query businessReq.EmailTemplateSearch true "分页获取短息模板列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /emailTemplate/getEmailTemplateList [get]
func (emailTemplateApi *EmailTemplateApi) GetEmailTemplateList(c *gin.Context) {
	var pageInfo businessReq.EmailTemplateSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userId := utils.GetUserID(c)
	pageInfo.UserId = userId
	if list, total, err := emailTemplateService.GetEmailTemplateInfoList(pageInfo); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}

// AdminGetEmailTemplateList 管理员分页获取企业分类列表
// @Tags Classify
// @Summary 分页获取企业分类列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query businessReq.ClassifySearch true "分页获取企业分类列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /classify/adminGetEmailTemplateList [get]
func (emailTemplateApi *EmailTemplateApi) AdminGetEmailTemplateList(c *gin.Context) {
	//判断是否是管理员，根据不同身份返回不同的值
	isAdmin := utils.GetUserIsAdmin(c)
	var pageInfo businessReq.EmailTemplateSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if isAdmin == 1 {
		list, total, err := emailTemplateService.GetEmailTemplateInfoList(pageInfo)
		if err != nil {
			global.GVA_LOG.Error("获取失败!", zap.Error(err))
			response.FailWithMessage("获取失败", c)
			return
		}
		//赋值
		var emailTemplateAdminQueryList []businessRes.EmailTemplateAdminQuery
		err = copier.Copy(&emailTemplateAdminQueryList, &list)
		if err != nil {
			global.GVA_LOG.Error("赋值时发生错误!", zap.Error(err))
			response.FailWithMessage("赋值时发生错误", c)
			return
		}

		//附带用户信息
		//定义用户数组
		var userIdList []uint
		for _, v := range emailTemplateAdminQueryList {
			userIdList = append(userIdList, v.UserId)
		}
		userList, err := userService.FindUserByIdList(userIdList)
		if err != nil {
			global.GVA_LOG.Error("获取用户信息失败!", zap.Error(err))
			response.FailWithMessage("获取用户信息失败", c)
		}
		//定义用户map
		userMap := make(map[uint]businessRes.UserInfo)
		for _, v := range userList {
			userMap[v.ID] = businessRes.UserInfo{
				ID:       v.ID,
				NickName: v.NickName,
				Username: v.Username,
			}
		}

		for k, v := range emailTemplateAdminQueryList {
			emailTemplateAdminQueryList[k].UserInfo = userMap[v.UserId]
		}

		response.OkWithDetailed(response.PageResult{
			List:     emailTemplateAdminQueryList,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	} else {
		response.FailWithMessage("你没有权限", c)
	}
}
